﻿using cn.bmob.api;
using cn.bmob.exception;
using cn.bmob.io;
using cn.bmob.response;
using System;
using System.Collections.Generic;

namespace _65_练习_Bmob后端云
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            //创建Bmob对象
            BmobWindows bmob = new BmobWindows();
            //初始化(给他appkey和restkey)  从网站上我们简历的App中拿
            bmob.initialize("db5c9b63e0c857a249be3836c06e1f16", "6b8e1160ecd34c1eec3d78304ef2807c");

            //测试增加数据
            // TestCreat(bmob);

            //测试查询数据
            TestQuery(bmob);

            Console.ReadLine();
            string
        }

        private static void TestQuery(BmobWindows bmob)
        {
            BmobQuery query = new BmobQuery();
            query.WhereGreaterThan("age", 20);

            bmob.Find<Student>("Student", query, QueryCallBack);
        }

        private static void QueryCallBack(QueryCallbackData<Student> response, BmobException exception)
        {
            if (exception != null)
            {
                Console.WriteLine("查询失败:" + exception.Message);
                return;
            }
            List<Student> list = response.results;
            foreach (var item in list)
            {
                Console.WriteLine(item.ToString());
            }
        }

        private static void TestCreat(BmobWindows bmob)
        {
            Student stu1 = new Student("周杰伦", 40);
            //BmobApi地址:http://doc.bmob.cn/data/csharp/develop_doc/
            bmob.Create(stu1, OnEnd);//增加一行数据 ,OnEnd是回调函数,用来判断是否成功,获取取服务器发回来的数据
        }

        private static void OnEnd(CreateCallbackData response, BmobException exception)
        {
            if (exception != null)
            {
                Console.WriteLine(exception.Message);
            }
            else
            {
                Console.WriteLine("创建数据行成功");
            }
        }
    }

    //数据模型类,需要先再Bmob服务端创建Student表,并增加name,age两个列
    internal class Student : BmobTable
    {
        public string name;
        public int age;

        public Student()
        {
        }

        public Student(string name, int age)
        {
            this.name = name;
            this.age = age;
        }

        public override void readFields(BmobInput input)
        {
            base.readFields(input);
            this.name = input.getString("name");
            this.age = input.getInt("age").Get();
        }

        public override void write(BmobOutput output, bool all)
        {
            base.write(output, all);

            output.Put("name", name);
            output.Put("age", age);
        }

        public override string ToString()
        {
            return name + ":" + age;
        }
    }
}